
#include <Inklude/ikCTcpServer.h>
#include <Inklude/Internal/ikCTcpBoost.h>


using namespace Inklude;
using namespace Inklude::Internal;

ikCTcpServer::ikCTcpServer()
{
}

ikCTcpServer::~ikCTcpServer()
{
}

bool ikCTcpServer::OpenServer(unsigned int nPort)
{
    bool retVal = true;
    m_nListenPort = nPort;
    if (m_pTcp.use_count() == 0)
    {
        m_pTcp.reset(new ikCTcpBoost);
    }
    try
    {
        m_pTcp->Initialize(m_nListenPort);
    }
    catch (...)
    {
        printf("Open Server Error\n");
        retVal = false;
    }
    return retVal;
}

const ikCTcpClientPtr ikCTcpServer::CheckNewConnection()
{
    m_pTcp->Accept();
    return _getAcceptedClientPtr();
}

void ikCTcpServer::AsyncCheckNewConnection(CheckNewConnectionHandler endHandler)
{
    std::shared_ptr<std::function<void(size_t)> > handler(new std::function<void(size_t)>([=](size_t param)
    {
        auto _ptr = _getAcceptedClientPtr();
        (*endHandler)(_ptr);
    }));
    m_pTcp->AsyncAccept(handler);
    m_pTcp->Run();
}

const ikCTcpClientPtr ikCTcpServer::_getAcceptedClientPtr()
{
    auto tmpBoostTcp = m_pTcp;
    ikCTcpClientPtr _ptr(new ikCTcpClient(m_pTcp));
    m_pTcp.reset(new ikCTcpBoost(tmpBoostTcp->m_pIOService, tmpBoostTcp->m_pAcceptor));
    m_pTcp->Initialize(m_nListenPort);
    return _ptr;
}

